<template>
  <div class="person">
    <el-form :model="formData" label-width="auto" style="max-width: 600px" :rules="rules" ref="formRef">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" style="width:70%;"/>
        <img :src="codeSrc" alt="" @click="getCode" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button type="primary" @click="getUserInfo">获取用户信息</el-button>
        <el-button type="primary" @click="logout">退出登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup name="LoginDemo">
import { onMounted, ref, reactive, nextTick } from 'vue'
import { type FormRules, type ElForm, ElMessage } from 'element-plus';
import { useUserStore  } from "@/stores/user";
import { useRouter } from "vue-router";
import { getCodeImg, getUser } from "@/api/login";
import { encryptAES } from '@/utils/crypto'

onMounted(() => {
  getCode();
});
const userStore = useUserStore();
const router = useRouter();
interface Form {
  name: string
  password: string
  code: string
}
const formRef = ref<InstanceType<typeof ElForm>>();
const formData = ref<Form>({
  name: 'lixb',
  password: 'lixb123',
  code: ''
});
const codeSrc = ref('');
const codeText = ref('');
const getCode = () => {
  getCodeImg().then((res) => {
    codeSrc.value = res.data.base64;
    codeText.value = res.data.text;
  });
};
const judgeName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback();
  }
  if (value === '张三') {
    callback(new Error('用户名不能为张三'));
  } else {
    callback();
  }
};
const rules = reactive<FormRules<Form>>({
  name: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { validator: judgeName, trigger: 'blur' },
  ],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
});
const validateForm = (): Promise<boolean> => {
  return new Promise((resolve) => {
    nextTick(() => {
      formRef
        .value!.validate()
        .then(() => {
          resolve(true);
        })
        .catch((error) => {
          formRef.value!.scrollToField(Object.keys(error)[0]);
          resolve(false);
        });
    });
  });
};
const onSubmit = async () => {
  const validate = await validateForm();
  if (!validate) return;
  if(formData.value.code !== codeText.value) {
    ElMessage({
      message: "验证码不正确！",
      type: "warning",
    });
    getCode();
  } else {
    const { name, password } = formData.value
    userStore.login(name, encryptAES(password)).then(() => {
      router.push('/');
    }).catch(() => {
      getCode();
    })
  }
}
const getUserInfo = () => {
  getUser(userStore.userId).then((res:any) => {
    console.log('用户信息', res);
    ElMessage({
      message: "获取用户信息成功！",
      type: "success",
    });
  })
}
const logout = () => {
  userStore.logout();
}
</script>
<style scoped lang="scss">
img{
  width: 86px;
  height: 32px;
  margin-left: 20px;
  cursor: pointer;
}
</style>